#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

import tempfile
import sys
import os
import _winreg
import time
from PySide import QtCore, QtGui
from .grabrect import GrabRect
from .ui.menuwidget import MenuWidget
from .pyuic import resources_rc
class ScreenGrabber(QtGui.QDialog):
    """
    A transparent tool dialog for selecting an area (QRect) on the screen.

    This tool does not by itself perform a screen capture. The resulting
    capture rect can be used (e.g. with the get_desktop_pixmap function) to
    blit the selected portion of the screen into a pixmap.
    """
    # If set to a callable, it will be used when performing a
    # screen grab in place of the default behavior defined in
    # this module.
    SCREEN_GRAB_CALLBACK = None

    def __init__(self, parent=None):
        """
        Constructor
        """
        super(ScreenGrabber, self).__init__(parent)
        self.start_pos = None#QtCore.QPoint(0,0)#QtGui.QCursor.pos()
        self.end_pos = None#QtCore.QPoint(0,0)#QtGui.QCursor.pos()
        self._opacity = 1
        self._draw = None
        self._click = None
        self._menu_pos = None
        self._capture_rect = QtCore.QRect()


        self.setWindowFlags(QtCore.Qt.FramelessWindowHint |
                            QtCore.Qt.WindowStaysOnTopHint |
                            QtCore.Qt.CustomizeWindowHint |
                            QtCore.Qt.Tool)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setCursor(QtCore.Qt.CrossCursor)
        self.setMouseTracking(True)

        ###############################################################################
        self.grabRect = GrabRect(self)
        self.grabRect.setObjectName('grabRect')
        self.grabRect.setVisible(0)
        self.grabRect.setStyleSheet("QFrame#grabRect{background-color:rgba(255,0,0,1);}")
        #self.grabRect.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        self.menu_widget = MenuWidget(self)#QtGui.QFrame(self)
        self.menu_widget.setStyleSheet("QFrame{background-color:rgb(200,200,200);}")
        self.menu_widget.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        self.menu_widget.setVisible(0)
        ###############################################################################

        desktop = QtGui.QApplication.instance().desktop()
        desktop.resized.connect(self._fit_screen_geometry)
        desktop.screenCountChanged.connect(self._fit_screen_geometry)


    @property
    def capture_rect(self):
        """
        The resulting QRect from a previous capture operation.
        """
        return self._capture_rect

    def save_image(self):
        file_dialog = QtGui.QFileDialog()
        desktop_path = get_desktop()
        default_path = os.path.join(desktop_path, 'ScreenGrab.png').replace('\\', '/')
        print default_path
        result_path = file_dialog.getSaveFileName(self, 'Save Image', default_path, 'Image Files (*.png, *.jpg, *.bmp)')[0]
        print result_path
        if not result_path:
            return
        time.sleep(0.5)
        self.close()
        pm = get_desktop_pixmap(self.capture_rect)
        pm.save(result_path)


    def paintEvent(self, event):
        """
        Paint event
        """
        # Convert click and current mouse positions to local space.
        painter = QtGui.QPainter(self)
        # Draw background. Aside from aesthetics, this makes the full
        # tool region accept mouse events.
        painter.setBrush(QtGui.QColor(0, 0, 0, self._opacity))
        painter.setPen(QtCore.Qt.NoPen)
        painter.drawRect(event.rect())

        ################################
        try:
            pos = []
            if self.start_pos.x() > self.end_pos.x():
                if self.start_pos.y() < self.end_pos.y():
                    start_p = QtCore.QPoint(self.end_pos.x(), self.start_pos.y())
                    end_p = QtCore.QPoint(self.start_pos.x(), self.end_pos.y())
                    capture_rect = QtCore.QRect(start_p, end_p)
                    pos = [self.end_pos.x(), self.end_pos.y()]
                else:
                    capture_rect = QtCore.QRect(self.end_pos, self.start_pos)
                    pos = [self.end_pos.x(), self.start_pos.y()]
            else:
                if self.start_pos.y() > self.end_pos.y():
                    start_p = QtCore.QPoint(self.start_pos.x(), self.end_pos.y())
                    end_p = QtCore.QPoint(self.end_pos.x(), self.start_pos.y())
                    capture_rect = QtCore.QRect(start_p, end_p)
                    pos = [self.start_pos.x(), self.start_pos.y()]
                else:
                    capture_rect = QtCore.QRect(self.start_pos, self.end_pos)
                    pos = [self.start_pos.x(), self.end_pos.y()]
            painter.setCompositionMode(QtGui.QPainter.CompositionMode_Clear)
            painter.drawRect(capture_rect)
            painter.setCompositionMode(QtGui.QPainter.CompositionMode_SourceOver)
            pen = QtGui.QPen(QtGui.QColor(255, 255, 255, 64), 1, QtCore.Qt.DotLine)
            painter.setPen(pen)
            if self._draw:
                painter.drawLine(self.rect().left(), self.start_pos.y(),
                                 self.rect().right(), self.start_pos.y())
                painter.drawLine(self.start_pos.x(), self.rect().top(),
                                 self.start_pos.x(), self.rect().bottom())

                painter.drawLine(self.rect().left(), self.end_pos.y(),
                                 self.rect().right(), self.end_pos.y())
                painter.drawLine(self.end_pos.x(), self.rect().top(),
                                 self.end_pos.x(), self.rect().bottom())
                self.update()

            if not self._draw :
                return
            self.grabRect.setGeometry(capture_rect)
            if self.grabRect.mapToGlobal(self.grabRect.rect().bottomRight()).y() + 37> self.mapToGlobal(self.rect().bottomRight()).y():
                if self.grabRect.mapToGlobal(self.grabRect.rect().topLeft()).y() - 37 < self.mapToGlobal(self.rect().topLeft()).y():
                    pos = self.grabRect.mapToGlobal(self.grabRect.rect().topLeft())
                    self.menu_widget.move(pos.x()+2, pos.y()+2)
                else:
                    pos = self.grabRect.mapToGlobal(self.grabRect.rect().topLeft())
                    self.menu_widget.move(pos.x()+2, pos.y()-38)
            else:
                self.menu_widget.move(pos[0]+2, pos[1]+2)
        except:pass

    def keyPressEvent(self, event):
        pass

    def mousePressEvent(self, event):
        """
        Mouse click event
        """

        if event.button() == QtCore.Qt.LeftButton:
            self._click = True

            self._draw = True
            self.start_pos = self.mapFromGlobal(event.globalPos())

    def mouseReleaseEvent(self, event):
        """
        Mouse release event
        """
        self._click = None
        if event.button() == QtCore.Qt.LeftButton and self._click is not None:
            # End click drag operation and commit the current capture rect
            self._capture_rect = QtCore.QRect(self.start_pos,
                                              event.globalPos()).normalized()
        self._capture_rect = QtCore.QRect(self.start_pos,
                                          event.globalPos()).normalized()
        self._draw = None
        #
        # if self.end_pos:
        #     self.grabRect.setVisible(1)
        #     self.menu_widget.setVisible(1)


    def mouseMoveEvent(self, event):
        """
        Mouse move event
        """
        if not self._click:
            return
        self.grabRect.setVisible(1)
        self.menu_widget.setVisible(1)

        self.end_pos = self.mapFromGlobal(event.globalPos())
        self.repaint()

    def showEvent(self, event):
        """
        Show event
        """
        self._fit_screen_geometry()
        # Start fade in animation
        fade_anim = QtCore.QPropertyAnimation(self, "_opacity_anim_prop", self)
        fade_anim.setStartValue(self._opacity)
        fade_anim.setEndValue(170)
        fade_anim.setDuration(300)
        fade_anim.setEasingCurve(QtCore.QEasingCurve.OutCubic)
        fade_anim.start(QtCore.QAbstractAnimation.DeleteWhenStopped)

    def _set_opacity(self, value):
        """
        Animation callback for opacity
        """
        self._opacity = value
        self.repaint()

    def _get_opacity(self):
        """
        Animation callback for opacity
        """
        return self._opacity

    _opacity_anim_prop = QtCore.Property(int, _get_opacity, _set_opacity)

    def _fit_screen_geometry(self):
        # Compute the union of all screen geometries, and resize to fit.
        desktop = QtGui.QApplication.instance().desktop()
        workspace_rect = QtCore.QRect()
        for i in range(desktop.screenCount()):
            workspace_rect = workspace_rect.united(desktop.screenGeometry(i))
        self.setGeometry(workspace_rect)
        #self.setGeometry(0,0,600,600)
def get_desktop():
    key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,\
                          r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',)
    return _winreg.QueryValueEx(key, "Desktop")[0]

def get_desktop_pixmap(rect):
    """
    Performs a screen capture on the specified rectangle.

    :param rect: Rectangle to capture
    :type rect: :class:`~PySide.QtCore.QRect`
    :returns: Captured image
    :rtype: :class:`~PySide.QtGui.QPixmap`
    """
    desktop = QtGui.QApplication.instance().desktop()
    return QtGui.QPixmap.grabWindow(desktop.winId(), rect.x(), rect.y(),
                                    rect.width(), rect.height())
